package cn.vc.wallet.service.impl;

import cn.vc.basicmodule.entity.Result;
import cn.vc.wallet.entity.dto.WalletDto;
import cn.vc.wallet.entity.po.TopUp;
import cn.vc.wallet.entity.po.Wallet;
import cn.vc.wallet.mapper.TopUpMapper;
import cn.vc.wallet.mapper.WalletMapper;
import cn.vc.wallet.service.TopUpService;
import cn.vc.wallet.service.WalletService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author mo
 * @Description:
 * @日期: 2024-04-20 18:04
 **/
@Slf4j
@Service
public class TopUpServiceImpl implements TopUpService {
    // KEY{id}
    private final static String TOP_UP_KEY = "topup:";

    @Autowired
    private TopUpMapper topUpMapper;
    @Autowired
    private WalletMapper walletMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public void add(TopUp topUp) {
        topUpMapper.insert(topUp);
    }

    @Override
    public TopUp selectById(String id) {
        TopUp topUp = JSON.parseObject(stringRedisTemplate.opsForValue().get(TOP_UP_KEY +id), TopUp.class);
        if (topUp==null) {
            topUp = topUpMapper.selectById(id);
            stringRedisTemplate.opsForValue().set(TOP_UP_KEY +id, JSON.toJSONString(topUp), 30, TimeUnit.SECONDS);
        }
        return topUp;
    }

    @Override
    public void paymentCompletion(String id, String alipay_trade_no) {
        TopUp topUp = selectById(id);
        if (topUp==null) return;
        if (alipay_trade_no==null) {
            log.error("订单号：{}，支付宝流水号为空！", id);
            throw new RuntimeException("支付宝流水号为空！");
        }
        // 添加支付宝流水号
        topUp.setAlipayTradeNo(alipay_trade_no);
        // 修改为支付草稿
        topUp.setPay_or_not(true);
        // 向钱包添加钻石
        Wallet wallet = walletMapper.selectById(topUp.getUserId());
        wallet.setDiamond(wallet.getDiamond()+topUp.getDiamond());
        // 修改数据库
        walletMapper.updateById(wallet);
        topUpMapper.updateById(topUp);
    }


}
